package help

import (
	"database/sql"
	"encoding/json"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"os"
	"time"
	"net/http"
	"html/template"
)

type ConfigExt struct {
	Address      string
	ReadTimeOut  int64
	WriteTimeOut int64
	Static       string
	StaticUrl    string
}

var WebConfig ConfigExt
var Logger *log.Logger
var Db *sql.DB

//初始化函数
func init() {
	//首先加载配置文件
	loadConfig()
	//配置日志
	file, err := os.OpenFile("logs/"+time.Now().Format("2006-01-02")+".log", os.O_CREATE|os.O_RDONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Println("加载日志文件出错", err)
	}
	Logger = log.New(file, "INFO", log.Ldate|log.Ltime|log.Lshortfile)
	//注册数据库
	Db, err = sql.Open("mysql", "root:root@tcp(127.0.0.1:3306)/newgice")
	CheckError(err, "连接数据库失败")
}

//打印帮助函数
func P(str ...interface{}) {
	fmt.Println(str)
}

func loadConfig() {
	file, err := os.Open("config/app.json")
	if err != nil {
		log.Println("加载配置文件出错", err)
	}
	decoder := json.NewDecoder(file)
	WebConfig = ConfigExt{}
	err = decoder.Decode(&WebConfig)
	if err != nil {
		log.Println("解析配置文件出错", err)
	}
}

func CheckError(err error, errmsg string) {
	if err != nil {
		Logger.Println("出错了,错误信息"+errmsg, err)
	}
}

//解析模板文件
func ParseTemplate(write http.ResponseWriter,temp string,data interface{},filenames ...string) {
	var files []string
	for _,file := range filenames {
		files = append(files,fmt.Sprintf("template/%s.html",file))
	}
	templates := template.Must(template.ParseFiles(files...))
	templates.ExecuteTemplate(write,temp,data)
}

//返回程序版本号
func GetVersion() string {
	return "1.0.0"
}
